package com.lagou.component;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * 注册器
 *
 */
public class Register {

    private CuratorFramework client;

    public Register() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(3000)
                .connectionTimeoutMs(3000)
                .retryPolicy(retryPolicy)
                .namespace("Register")
                .build();
        client.start();
    }

    /**
     * 注册地址信息
     *
     * @param address
     */
    public void register(String address) {
        String path = "/ServerBootstrap/Provider";
        String nodeName;
        try {
            nodeName = client.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                    .forPath(path, address.getBytes());
        } catch (Exception e) {
            throw new IllegalStateException("注册失败");
        }
        System.out.println(String.format("注册成功,注册信息：%s, 节点名称：%s", address, nodeName));
    }

}
